import { NestFactory } from '@nestjs/core'
import rateLimit from 'express-rate-limit'
import helmet from 'helmet'
import { generateDocument } from './doc'
import { AppModule } from './app.module'
import { HttpExceptionFilter } from './shared/core/filters/HttpExceptionFilter'
import { ResponseInterceptor } from './shared/core/interceptors/response.interceptor'
import { ValidationPipe } from '@nestjs/common'
import { json, urlencoded } from 'express'
import { NestExpressApplication } from '@nestjs/platform-express'

declare const module: any

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule)

  // 接口版本化管理
  // app.enableVersioning({
  //   defaultVersion: '1',
  //   type: VersioningType.URI,
  // })

  // 设置访问频率
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15分钟
      max: 1000, // 限制15分钟内最多只能访问1000次
    }),
  )

  app.enableCors()
  app.setGlobalPrefix('api')

  // web 安全，防常见漏洞
  app.use(helmet.crossOriginResourcePolicy({ policy: 'cross-origin' }))

  // 全局注册错误的过滤器
  app.useGlobalFilters(new HttpExceptionFilter())
  app.useGlobalInterceptors(new ResponseInterceptor())
  app.useGlobalPipes(new ValidationPipe({ transform: true }))

  // 设置静态目录
  app.useStaticAssets('public', {
    prefix: '/static/',
  })

  // 文件上传大小限制
  app.use(json({ limit: '5mb' }))
  app.use(urlencoded({ extended: true, limit: '5mb' }))

  // 创建文档
  generateDocument(app)
  await app.listen(3000)

  // 热更新
  if (module.hot) {
    module.hot.accept()
    module.hot.dispose(() => app.close())
  }
}
bootstrap()
